@namespace BulmaRazor.Components
@inherits BulmaComponentBase
@inject NavigationManager nm

<aside id="@Id" @attributes="Attributes" class="@classes">
    <CascadingValue Value="this" IsFixed="true">
        @ChildContent
    </CascadingValue>
</aside>

@code{

    internal readonly string Id = "menu_" + Guid.NewGuid().ToString("N");

    string classes => CssBuilder.Default("menu")
        .AddClassFromAttributes(Attributes)
        .Build();

    private List<MenuItem> items = new();

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public EventCallback<MenuItem> OnItemClick { get; set; }

    internal void AddItem(MenuItem item)
    {
        items.Add(item);
    }
    
    internal async Task ClickItem(MenuItem menuItem)
    {
        foreach (var item in items)
        {
            item.Title.Active(item == menuItem);
        }
        await OnItemClick.InvokeAsync(menuItem);
    }

    protected override void OnAfterRender(bool firstRender)
    {
        foreach (var item in items)
        {
            if (item?.Title?.Href != null)
            {
                if (nm.Uri.EndsWith(item.Title.Href ?? string.Empty, StringComparison.OrdinalIgnoreCase))
                {
                    item.Title.Active(true);
                    break;
                }
            }
        }
        base.OnAfterRender(firstRender);
    }

}